package com.glinsoft.ticktak.service;

import com.glinsoft.ticktak.entity.Cluster;
import com.glinsoft.ticktak.mapper.ClusterMapper;
import com.glinsoft.ticktak.vo.ClusterVo;

import com.glinsoft.waterbatis.query.Page;
import com.glinsoft.waterbatis.query.Query;

import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;


@Data
@Service
public class ClusterService {
    @Autowired
    private ClusterMapper mapper;

    public ClusterService() {
    }

    public ClusterService(ClusterMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 保存数据记录
     * @param o
     * @return 返回新增记录的主键
     */
    public String save(ClusterVo o) {
        Cluster po = o.toPO();
        mapper.insert(po);

        return po.getId();
    }

    /**
     * 批量增添记录
     * @param list 待存储记录列表
     */
    public void saveBatch(List<ClusterVo> list) {
        mapper.insertBatch(ClusterVo.toPO(list));
    }

    /**
     * 根据ID，单个更新
     * @param o
     */
    public void update(ClusterVo o) {
        mapper.update(o.toPO());
    }

    /**
     * 批量更新
     * @param list
     */
    public void updateBatch(List<ClusterVo> list) {
        for (ClusterVo o : list) {
            mapper.update(o.toPO());
        }
    }

    /**
     * 按照ID删除
     * @param id
     */
    public void delete(String id) {
        mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param list
     */
    public void deleteBatch(List<String> list) {
        for (String id : list) {
            mapper.deleteById(id);
        }
    }

    /**
     * 统计表中记录总数
     * @return 表记录总数
     */
    public Long count() {
        return mapper.getCount(new Query());
    }

    /**
     * 按照页码查询
     * @param pageIndex 当前第几页
     * @param pageSize 每页显示数据数
     * @return 返回查询页的数据
     */
    public Page<ClusterVo> listPage(int pageIndex, int pageSize) {
        long total = count();
        List<Cluster> data = mapper.list(new Query().page(pageIndex, pageSize));

        return Page.<ClusterVo>builder().pageIndex(pageIndex).pageSize(pageSize)
                   .total(total)
                   .pageTotal(((total % pageSize) == 0L)
            ? (int) (total / pageSize) : (int) ((total / pageSize) + 1))
                   .data(ClusterVo.fromPO(data)).build();
    }

    /**
     * 按照主键查询
     * @param id
     * @return
     */
    public ClusterVo get(String id) {
        return ClusterVo.fromPO(mapper.getById(id));
    }
}
